//
//  PictureTableViewController.m
//  CarHome
//
//  Created by lanou3g on 15-5-1.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "PictureTableViewController.h"
#import "Picture.h"
#import "PicCategory.h"
#import "PicColor.h"
#import "PicDefault.h"
#import "PicList.h"
#import "PicSpecification.h"
#import "PictureTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "PictureShowAllCollectionViewController.h"
#import "PictureShowOneViewController.h"

@interface PictureTableViewController ()

@property (nonatomic, retain) Picture *pic;


@end

@implementation PictureTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"PictureTableViewCell" bundle:nil] forCellReuseIdentifier:@"PictureTableViewCellIdentifier"];
    
    self.defaultpiclist = [NSMutableArray array];
}

- (void)loadData {
    if (_defaultpiclist.count == 0) {
        [self.tableView addMyActivityIndicatorView];
        NSLog(@"%@", pictureURLwithCarID(_seriesID));
        __block typeof(self) weakSelf = self;
        
        [HTTPRequest requestWithURL:pictureURLwithCarID(_seriesID) method:@"GET" result:^(NSData *data) {
            NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            self.pic = [[Picture new] autorelease];
            [_pic setValuesForKeysWithDictionary:dict[@"result"]];
            
            self.defaultpiclist = [[NSMutableArray alloc]initWithArray:_pic.defaultpiclist];
            [self.view removeMyActivityIndicatorViewFromSuperView];
            [weakSelf.tableView reloadData];
        }];
    } else {
        [self.tableView reloadData];
    }
    

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.defaultpiclist.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PictureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PictureTableViewCellIdentifier"];
    UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(testAction:)];
    [cell.checkall addGestureRecognizer:tgr];
    PicDefault *pd = _defaultpiclist[indexPath.row];
    cell.name.text = pd.name;
    cell.piccount.text = [NSString stringWithFormat:@"%@张", pd.total];
    NSMutableArray *list = [[NSMutableArray alloc] initWithArray:pd.list];
    NSMutableArray *images = [[NSMutableArray alloc] initWithObjects:cell.image1, cell.image2, cell.image3, cell.image4, cell.image5, cell.image6, nil];
    for (int i = 0; i < list.count; i++) {
        PicList *pl = list[i];
        [images[i] sd_setImageWithURL:[NSURL URLWithString:pl.smallpic] placeholderImage:[UIImage imageNamed:@"default_180*136"]];
        UITapGestureRecognizer *tgr2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapAction:)];
        [images[i] addGestureRecognizer:tgr2];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 220;
}

- (void)testAction:(UITapGestureRecognizer *)sender {
    UICollectionViewFlowLayout *flowLayout = [UICollectionViewFlowLayout new];
    flowLayout.itemSize = CGSizeMake((kWIDTH  - 40) / 3, 70);
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.minimumLineSpacing = 10;
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;

    PictureShowAllCollectionViewController *picShowAllCVC = [[PictureShowAllCollectionViewController alloc] initWithCollectionViewLayout:flowLayout];
    PictureTableViewCell *cell = (PictureTableViewCell *)sender.view.superview.superview;
    // xib 自定义cell情况   第一个superview是contentView，第二个superview是自定义cell，第三个superview是UITableView的cell，，注意不要弄混淆了。
//    NSLog(@"=========%@",sender.view.superview.superview);
//    NSLog(@"%lu", [self.tableView indexPathForCell:cell].row);
    picShowAllCVC.seriesID = _seriesID;
    picShowAllCVC.rowIndex = [self.tableView indexPathForCell:cell].row;

    
//    UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:picShowAllCVC];
    [self.navigationController pushViewController:picShowAllCVC animated:YES];
    
}

- (void)imageTapAction:(UITapGestureRecognizer *)sender {
    
    UIImageView *imageView = (UIImageView *)sender.view;
    PictureTableViewCell *cell = (PictureTableViewCell *)imageView.superview.superview;
    NSMutableArray *images = [[NSMutableArray alloc] initWithObjects:cell.image1, cell.image2, cell.image3, cell.image4, cell.image5, cell.image6, nil];

    NSMutableArray *urls = [[[NSMutableArray alloc] initWithObjects:pictureURLwithCarID_1(_seriesID), pictureURLwithCarID_2(_seriesID), pictureURLwithCarID_3(_seriesID), pictureURLwithCarID_4(_seriesID), pictureURLwithCarID_5(_seriesID), nil] autorelease];
    NSInteger rowIndex = [self.tableView indexPathForCell:cell].row;
    
    [HTTPRequest requestWithURL:urls[rowIndex] method:@"GET" result:^(NSData *data) {
        NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        Picture *p = [[Picture new] autorelease];
        [p setValuesForKeysWithDictionary:dict[@"result"]];
        
        NSMutableArray *picList = [[NSMutableArray alloc] initWithArray:p.piclist];
        PictureShowOneViewController *picShowOne = [[PictureShowOneViewController new] autorelease];
        picShowOne.row = [images indexOfObject:imageView];
        picShowOne.picList = picList;
        [self.navigationController presentViewController:picShowOne animated:YES completion:nil];
    }];
}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
